package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"icasset/internal/dao"   // 替换为你的项目路径
	"icasset/internal/model" // 替换为你的项目路径
	"net/http"
)

// UserHandler 结构体，持有 GORM DAO 作为依赖
type UserHandler struct {
	// 我们推荐注入 DAO 层，而不是直接注入 *gorm.DB，这更符合分层架构
	userDAO *dao.GormUserDAO
}

// NewUserHandler 是一个构造函数，用于创建 UserHandler 实例并注入依赖
func NewUserHandler(userDAO *dao.GormUserDAO) *UserHandler {
	return &UserHandler{userDAO: userDAO}
}

// CreateUser 是 Gin 的路由处理器方法
func (h *UserHandler) CreateUser(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 通过 h.userDAO 安全地访问数据库
	if err := h.userDAO.AddUser(&user); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user: " + err.Error()})
		return
	}

	c.JSON(http.StatusCreated, user)
}

func (h *UserHandler) GetAllUsers(c *gin.Context) {

	users, err := h.userDAO.GetAllUsers()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get users: " + err.Error()})
		return
	}
	c.JSON(http.StatusCreated, users)
}

func (h *UserHandler) Login(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	validateUser, tokenString, err := h.userDAO.Login(user.LoginName, user.Password)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid login credentials"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "Login successful",
		"user":    validateUser,
		"token":   tokenString,
	})

}

func (h *UserHandler) Register(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	fmt.Println("login name:", user.LoginName)
	fmt.Println("password:", user.Password)
	if err := h.userDAO.Register(&user); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to register user: " + err.Error()})
		return
	}
	c.JSON(http.StatusCreated, user)
}
